package com.example.woke;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import com.bean.BaseResponse;
import com.http.HttpMethods;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.woke.adapter.InTheChannelListAdapter;
import com.woke.adapter.OnItemClickListener;
import com.woke.data.UnionPayChannel;
import com.woke.method.MyApp;
import com.woke.method.NetworkUtils;
import com.woke.serizedatas.Datas_load;
import com.zhongcai.online.R;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class InTheChannelListActivity extends AppCompatActivity implements XRecyclerView.LoadingListener {

    private MyApp application;
    private XRecyclerView mChannelRecyView;
    private InTheChannelListAdapter mChannelAdapter;
    private ArrayList<UnionPayChannel> mUnionPayChannels = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        setContentView(R.layout.activity_in_the_channel_list);
        initView();
        application = (MyApp) getApplication();

        getPayChannel();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updataPayChannel(int chanelWay) {
        if (chanelWay > 0 && mUnionPayChannels.size() > 0) {
            for (UnionPayChannel channel : mUnionPayChannels) {
                if (chanelWay == channel.getWay()) {
                    getPayChannel();
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void initView() {

        Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mChannelRecyView = (XRecyclerView) findViewById(R.id.channel_recyclerView);
        mChannelRecyView.setLoadingListener(this);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        layoutManager.setSmoothScrollbarEnabled(true);
        layoutManager.setAutoMeasureEnabled(true);
        mChannelRecyView.setLayoutManager(layoutManager);
        mChannelRecyView.setHasFixedSize(true);
        mChannelRecyView.setNestedScrollingEnabled(false);
        mChannelAdapter = new InTheChannelListAdapter(InTheChannelListActivity.this, mUnionPayChannels);
        mChannelAdapter.setOnItemClickListener(mItemClickListener);
        mChannelRecyView.setAdapter(mChannelAdapter);

    }

    @Override
    public void onRefresh() {
        mChannelRecyView.refreshComplete();
        if (NetworkUtils.isConnected(InTheChannelListActivity.this)) {
            getPayChannel();
        } else {
            showToast(getResources().getString(R.string.error_net2));
        }
    }

    @Override
    public void onLoadMore() {
        mChannelRecyView.loadMoreComplete();

    }

    private void getPayChannel() {
        Datas_load load = application.getDatas_load();
        if (load != null) {
            String userId = load.getId();
            HttpMethods.getInstance()
                    .gallery_list(mChannelObserver, Integer.parseInt(userId));
        }
    }

    private Observer<List<UnionPayChannel>> mChannelObserver = new Observer<List<UnionPayChannel>>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(List<UnionPayChannel> value) {
            if (value != null && value.size() > 0) {
                mUnionPayChannels.clear();
                mUnionPayChannels.addAll(value);
                if (mChannelAdapter != null) {
                    mChannelAdapter.notifyDataSetChanged();
                }
            }
        }

        @Override
        public void onError(Throwable e) {
            Toast.makeText(InTheChannelListActivity.this, "系统服务繁忙,请稍后重试", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onComplete() {

        }
    };

    private UnionPayChannel mSelectUnionPayChannel;
    private OnItemClickListener mItemClickListener = new OnItemClickListener() {
        @Override
        public void OnItemClick(View view, int position) {

        }

        @Override
        public void OnItemClick(View view, Object object, int position) {
            if (object instanceof UnionPayChannel) {
                mSelectUnionPayChannel = (UnionPayChannel) object;

                Datas_load load = application.getDatas_load();
                if (load != null) {
                    String userId = load.getId();
                    if (!TextUtils.isEmpty(userId) && userId.matches("[0-9]*")) {
                        if (mSelectUnionPayChannel.isGuangZhouPuFa()) {
                            //广州浦发
                            if (mSelectUnionPayChannel.isApprove()) {
                                //已经审核通过
                            } else {
                                if (NetworkUtils.isConnected(InTheChannelListActivity.this)) {
                                    HttpMethods.getInstance()
                                            .pufaAuthState(mStateObserver, Integer.parseInt(userId), mSelectUnionPayChannel.getWay());
                                } else {
                                    showToast(getResources().getString(R.string.error_net2));
                                }
                            }
                        } else if (mSelectUnionPayChannel.isHuiKa()) {
                            //广州汇卡
                            if (mSelectUnionPayChannel.isApprove()) {
                                //已经审核通过
                            } else {
                                if (NetworkUtils.isConnected(InTheChannelListActivity.this)) {
                                    HttpMethods.getInstance().isSettled(mHuiKaStateObserver, Integer.parseInt(userId), mSelectUnionPayChannel.getWay());
                                } else {
                                    showToast(getResources().getString(R.string.error_net2));
                                }
                            }
                        } else if (mSelectUnionPayChannel.isMinSheng()) {
//                            if (mSelectUnionPayChannel.isApprove()) {
//                                //已经审核通过
//                            } else if (mSelectUnionPayChannel.getSettled() == 1) {
//                                //审核中
//                                showToast(getResources().getString(R.string.ms_merchants_in_auth_ing));
//                            } else {
                                if (NetworkUtils.isConnected(InTheChannelListActivity.this)) {
                                    Intent intent = new Intent(InTheChannelListActivity.this,
                                            MinShengMerchantsInActivity.class);
                                    intent.putExtra("payway", mSelectUnionPayChannel.getPayway());
                                    intent.putExtra("way", mSelectUnionPayChannel.getWay());
                                    intent.putExtra("title", mSelectUnionPayChannel.getTitle());
                                    startActivity(intent);
                                } else {
                                    showToast(getResources().getString(R.string.error_net2));
                                }
//                            }
                        }
                    }
                }
            }
        }
    };

    private Toast mToast;

    private void showToast(String msg) {
        if (mToast == null) {
            mToast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
        }
        mToast.setText(msg);
        mToast.show();
    }

    private Observer<BaseResponse> mStateObserver = new Observer<BaseResponse>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(BaseResponse value) {
            if (value != null) {
                if (value.resultSuccess()) {
                    getPayChannel();//开通成功后，刷新列表
                }
                new AlertDialog.Builder(InTheChannelListActivity.this).setTitle("提示").setMessage(value.getInfo()).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).create().show();
            }
        }

        @Override
        public void onError(Throwable e) {
            if (e != null) {

                if ("in_the_review".equals(e.getMessage())) {
                    //审核中
                    new AlertDialog.Builder(InTheChannelListActivity.this).setTitle("审核中").setMessage(R.string.pufa_merchants_in_auth_ing).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).create().show();
                } else if ("idcardUnAuth".equals(e.getMessage())) {
                    //浦发 身份证照未审核通过
                    SwithFragmentActivity.newPufaIcCardAuthFragment(InTheChannelListActivity.this);

                } else if ("enterInfoUnAuth".equals(e.getMessage())) {
                    //浦发 未提交入驻信息
                    startActivity(new Intent(InTheChannelListActivity.this, PuFaMerchantsInActivity.class));
                }
            }
        }

        @Override
        public void onComplete() {

        }
    };


    private Observer<BaseResponse> mHuiKaStateObserver = new Observer<BaseResponse>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(BaseResponse value) {
            if (value != null) {
                if (value.resultSuccess()) {
                    //入驻成功
                    new AlertDialog.Builder(InTheChannelListActivity.this).setTitle("提示").setMessage(value.getInfo()).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            getPayChannel();
                        }
                    }).create().show();
                } else if ("60002".equals(value.getFlag())) {
                    //未需要提交商户入驻信息
                    if (mSelectUnionPayChannel != null) {
                        Intent intent = new Intent(InTheChannelListActivity.this, HuiKaMerchantsInActivity.class);
                        intent.putExtra("way", mSelectUnionPayChannel.getWay());
                        startActivity(intent);
                    }
                } else {
                    //unknow
                    //已入驻汇卡通道
                    showToast(value.getInfo());
                }
            }
        }

        @Override
        public void onError(Throwable e) {

        }

        @Override
        public void onComplete() {

        }
    };

}
